<?php
/**
 * 
 * Meshtiles API DataSource
 * @author tuanlq@lifetimetech.vn
 */

App::uses('MeshtilesApi', 'Lib\Meshtiles');

class MeshtilesSource extends DataSource {
	
	public $description = 'Meshtiles DataSource';
	
	/*
	 * Meshtiles Api class
	 * required: /app/Lib/Meshtiles/MeshtilesApi.php
	 */
	public $MeshtilesApi = null;
	
	public function __construct($config) {
		parent::__construct($config);
		$this->MeshtilesApi = new MeshtilesApi();
	}
	
	/**
	 * Implement the R in CRUD. Calls to ``Model::find()`` arrive here.
	 * @author tuanlq@lifetimetech.vn
	 */
	public function read(Model $Model, $data = array()) {
		/*
		 * param "methods" define the meshtiles api method.
		 */
		if (!isset($data['methods'])) {
			return false;
		}
		$response = $this->MeshtilesApi->callApi($data['methods'], $data['conditions'], $logging);
		
		if ($response === false) {
			return $logging;
		}
		
		$result = $response;
		
		if (isset($data['fields']) && is_array($data['fields'])) {
			foreach ($result as $field => $res) {
				if (in_array($field, $data['fields'])) {
					continue;
				}
				unset($result[$field]);
			}
		}
		
		return $result;
	}
	
}